// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
//materialManager (建材表云对象)
"use strict";

const db = uniCloud.database();
const dbCmd = db.command;
const materialsCollection = db.collection("materials");
const inboundOrdersCollection = db.collection("inbound_orders");
const outboundOrdersCollection = db.collection("outbound_orders");

module.exports = {
  _before: function () {
    // 通用预处理器
  },
  // 新增建材
  async addMaterial({ name, specification, supplier }) {
    const db = uniCloud.database();
    const res = await db.collection("materials").add({
      name,
      specification,
      supplier,
      createTime: new Date(),
    });
    return res;
  },

  /// 查询所有建材，过滤 status 等于 1
  async getMaterials() {
    const db = uniCloud.database();
    const res = await db
      .collection("materials")
      .where({
        status: 1, // 过滤 status 等于 1
        isDel: 0,
      })
      .get();
    return res.data;
  },

  // 删除建材
  async deleteMaterial({ materialId }) {
    const db = uniCloud.database();
    const res = await db.collection("materials").doc(materialId).remove();
    return res;
  },

  // 更新建材信息
  async updateMaterial({ materialId, name, specification, supplier }) {
    const db = uniCloud.database();
    const res = await db.collection("materials").doc(materialId).update({
      name,
      specification,
      supplier,
    });
    return res;
  },

  // 获取库存列表
  async getMaterialsStock() {
    return await materialsCollection.get();
  },

  // 创建入库订单
  async createInboundOrder(orderData) {
    // 计算总金额和付款信息
    orderData.totalAmount = orderData.quantity * orderData.price;

    // 添加支付相关字段（如果未提供）
    if (!orderData.hasOwnProperty("paidAmount")) {
      orderData.paidAmount = orderData.totalAmount; // 默认全额支付
      orderData.remainingAmount = 0;
      orderData.paymentStatus = "已支付";
    }

    orderData.createTime = Date.now();

    // 如果有付款记录，添加payments数组
    if (!orderData.payments && orderData.paidAmount > 0) {
      orderData.payments = [
        {
          amount: orderData.paidAmount,
          paymentDate: Date.now(),
        },
      ];
    }

    // 添加入库订单
    const orderResult = await inboundOrdersCollection.add(orderData);

    // 更新库存
    const material = await materialsCollection
      .where({
        manufacturer: orderData.manufacturer,
        specification: orderData.specification,
      })
      .get();

    if (material.data.length > 0) {
      // 更新现有库存
      await materialsCollection.doc(material.data[0]._id).update({
        quantity: dbCmd.inc(orderData.quantity),
        lastUpdated: Date.now(),
      });
    } else {
      // 创建新库存记录
      await materialsCollection.add({
        manufacturer: orderData.manufacturer,
        specification: orderData.specification,
        quantity: orderData.quantity,
        alertQuantity: 20, // 默认预警值
        unit: "吨",
        lastUpdated: Date.now(),
      });
    }

    return orderResult;
  },

  // 添加入库订单付款功能
  async addInboundPayment(orderId, paymentAmount) {
    const order = await inboundOrdersCollection.doc(orderId).get();
    if (!order.data) {
      throw new Error("未找到订单");
    }

    const orderData = order.data[0];
    if (paymentAmount > orderData.remainingAmount) {
      throw new Error("付款金额不能超过剩余金额");
    }

    const newPaidAmount = orderData.paidAmount + paymentAmount;
    const newRemainingAmount = orderData.totalAmount - newPaidAmount;
    const newPaymentStatus = newRemainingAmount <= 0 ? "已支付" : "未支付";

    // 更新订单
    return await inboundOrdersCollection.doc(orderId).update({
      paidAmount: newPaidAmount,
      remainingAmount: newRemainingAmount,
      paymentStatus: newPaymentStatus,
      payments: dbCmd.push({
        amount: paymentAmount,
        paymentDate: Date.now(),
      }),
    });
  },

  // 创建出库订单
  async createOutboundOrder(orderData) {
    // 计算总金额和剩余金额
    orderData.totalAmount = orderData.quantity * orderData.price;
    orderData.paidAmount = orderData.initialPayment || 0;
    orderData.remainingAmount = orderData.totalAmount - orderData.paidAmount;
    orderData.paymentStatus =
      orderData.remainingAmount <= 0 ? "已支付" : "未支付";
    orderData.createTime = Date.now();

    if (orderData.initialPayment > 0) {
      orderData.payments = [
        {
          amount: orderData.initialPayment,
          paymentDate: Date.now(),
        },
      ];
    } else {
      orderData.payments = [];
    }

    // 删除临时字段
    delete orderData.initialPayment;

    // 检查库存是否足够
    const material = await materialsCollection
      .where({
        manufacturer: orderData.manufacturer,
        specification: orderData.specification,
      })
      .get();

    if (
      material.data.length === 0 ||
      material.data[0].quantity < orderData.quantity
    ) {
      throw new Error("库存不足，无法出库");
    }

    // 添加出库订单
    const orderResult = await outboundOrdersCollection.add(orderData);

    // 更新库存
    await materialsCollection.doc(material.data[0]._id).update({
      quantity: dbCmd.inc(-orderData.quantity),
      lastUpdated: Date.now(),
    });

    return orderResult;
  },

  // 添加付款记录
  async addPayment(orderId, paymentAmount) {
    const order = await outboundOrdersCollection.doc(orderId).get();
    if (!order.data) {
      throw new Error("未找到订单");
    }

    const orderData = order.data[0];
    if (paymentAmount > orderData.remainingAmount) {
      throw new Error("付款金额不能超过剩余金额");
    }

    const newPaidAmount = orderData.paidAmount + paymentAmount;
    const newRemainingAmount = orderData.totalAmount - newPaidAmount;
    const newPaymentStatus = newRemainingAmount <= 0 ? "已支付" : "未支付";

    // 更新订单
    return await outboundOrdersCollection.doc(orderId).update({
      paidAmount: newPaidAmount,
      remainingAmount: newRemainingAmount,
      paymentStatus: newPaymentStatus,
      payments: dbCmd.push({
        amount: paymentAmount,
        paymentDate: Date.now(),
      }),
    });
  },

  // 获取入库订单列表（带分页）
  async getInboundOrders(filters = {}, page = 1, pageSize = 10) {
    let query = inboundOrdersCollection;

    // 应用筛选条件
    if (filters.manufacturer) {
      query = query.where({ manufacturer: filters.manufacturer });
    }

    if (filters.specification) {
      query = query.where({ specification: filters.specification });
    }

    if (filters.startDate && filters.endDate) {
      query = query.where({
        date: dbCmd.and([
          dbCmd.gte(filters.startDate),
          dbCmd.lte(filters.endDate),
        ]),
      });
    } else if (filters.startDate) {
      query = query.where({ date: dbCmd.gte(filters.startDate) });
    } else if (filters.endDate) {
      query = query.where({ date: dbCmd.lte(filters.endDate) });
    }

    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;

    // 分页查询
    const result = await query
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy("date", "desc")
      .get();

    return {
      data: result.data,
      total,
      hasMore: total > (page - 1) * pageSize + result.data.length,
    };
  },

  // 获取出库订单列表（带分页）
  async getOutboundOrders(filters = {}, page = 1, pageSize = 10) {
    let query = outboundOrdersCollection;

    // 应用筛选条件
    if (filters.manufacturer) {
      query = query.where({ manufacturer: filters.manufacturer });
    }

    if (filters.specification) {
      query = query.where({ specification: filters.specification });
    }

    if (filters.paymentStatus) {
      query = query.where({ paymentStatus: filters.paymentStatus });
    }

    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;

    // 分页查询
    const result = await query
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy("date", "desc")
      .get();

    return {
      data: result.data,
      total,
      hasMore: total > (page - 1) * pageSize + result.data.length,
    };
  },

  // 获取库存统计信息
  async getInventoryStatistics(filters = {}) {
    // 汇总库存数据
    const materials = await materialsCollection
      .aggregate()
      .match(filters) // 应用筛选条件
      .lookup({
        from: "inbound_orders",
        let: {
          manufacturer: "$manufacturer",
          specification: "$specification",
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ["$manufacturer", "$$manufacturer"] },
                  { $eq: ["$specification", "$$specification"] },
                ],
              },
            },
          },
        ],
        as: "inboundOrders",
      })
      .lookup({
        from: "outbound_orders",
        let: {
          manufacturer: "$manufacturer",
          specification: "$specification",
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ["$manufacturer", "$$manufacturer"] },
                  { $eq: ["$specification", "$$specification"] },
                ],
              },
            },
          },
        ],
        as: "outboundOrders",
      })
      .project({
        _id: 1,
        manufacturer: 1,
        specification: 1,
        quantity: 1,
        alertQuantity: 1,
        unit: 1,
        lastUpdated: 1,
        // 计算财务数据
        paidValue: {
          $sum: {
            $map: {
              input: {
                $filter: {
                  input: "$inboundOrders",
                  as: "order",
                  cond: { $eq: ["$$order.paymentStatus", "已支付"] },
                },
              },
              as: "order",
              in: "$$order.totalAmount",
            },
          },
        },
        unpaidValue: {
          $sum: {
            $map: {
              input: {
                $filter: {
                  input: "$inboundOrders",
                  as: "order",
                  cond: { $eq: ["$$order.paymentStatus", "未支付"] },
                },
              },
              as: "order",
              in: "$$order.remainingAmount",
            },
          },
        },
        totalSales: {
          $sum: {
            $map: {
              input: "$outboundOrders",
              as: "order",
              in: "$$order.totalAmount",
            },
          },
        },
      })
      .end();

    // 计算库存状态
    const result = materials.data.map((item) => {
      // 计算库存状态
      let status;
      if (item.quantity <= 0) {
        status = "缺货";
      } else if (item.quantity < item.alertQuantity) {
        status = "预警";
      } else if (item.quantity < item.alertQuantity * 2) {
        status = "适中";
      } else {
        status = "充足";
      }

      // 计算平均成本
      const totalValue = item.paidValue + item.unpaidValue;
      const avgCost = item.quantity > 0 ? totalValue / item.quantity : 0;

      return {
        ...item,
        status,
        value: Math.round(avgCost * item.quantity),
        avgCost: Math.round(avgCost * 100) / 100,
      };
    });

    return {
      data: result,
    };
  },

  // 获取按厂商统计的库存报表数据
  async getManufacturerStatistics() {
    const stats = await materialsCollection
      .aggregate()
      .group({
        _id: "$manufacturer",
        totalQuantity: { $sum: "$quantity" },
        items: { $push: "$$ROOT" },
      })
      .project({
        _id: 0,
        manufacturer: "$_id",
        totalQuantity: 1,
        specifications: {
          $map: {
            input: "$items",
            as: "item",
            in: {
              specification: "$$item.specification",
              quantity: "$$item.quantity",
            },
          },
        },
      })
      .end();

    return stats.data;
  },

  // 获取按规格统计的库存报表数据
  async getSpecificationStatistics() {
    const stats = await materialsCollection
      .aggregate()
      .group({
        _id: "$specification",
        totalQuantity: { $sum: "$quantity" },
        items: { $push: "$$ROOT" },
      })
      .project({
        _id: 0,
        specification: "$_id",
        totalQuantity: 1,
        manufacturers: {
          $map: {
            input: "$items",
            as: "item",
            in: {
              manufacturer: "$$item.manufacturer",
              quantity: "$$item.quantity",
            },
          },
        },
      })
      .end();

    return stats.data;
  },

  // 获取支付状态统计数据
  async getPaymentStatusStatistics() {
    // 获取入库订单的支付统计
    const inboundStats = await inboundOrdersCollection
      .aggregate()
      .group({
        _id: "$paymentStatus",
        totalAmount: { $sum: "$totalAmount" },
        paidAmount: { $sum: "$paidAmount" },
        remainingAmount: { $sum: "$remainingAmount" },
        count: { $sum: 1 },
      })
      .project({
        _id: 0,
        status: "$_id",
        totalAmount: 1,
        paidAmount: 1,
        remainingAmount: 1,
        count: 1,
      })
      .end();

    // 获取出库订单的支付统计
    const outboundStats = await outboundOrdersCollection
      .aggregate()
      .group({
        _id: "$paymentStatus",
        totalAmount: { $sum: "$totalAmount" },
        paidAmount: { $sum: "$paidAmount" },
        remainingAmount: { $sum: "$remainingAmount" },
        count: { $sum: 1 },
      })
      .project({
        _id: 0,
        status: "$_id",
        totalAmount: 1,
        paidAmount: 1,
        remainingAmount: 1,
        count: 1,
      })
      .end();

    return {
      inbound: inboundStats.data,
      outbound: outboundStats.data,
    };
  },
};
